package com.zhengxing.jienci.web.util.file;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 浪遏飞舟
 * @create 2020-10-31 14:51
 * 文件上传工具类
 */
@Component
public class FileUploadUtils {

    @Value("${uploadFile.dir}")
    private String uploadDir;

    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png", "JPEG",
            // word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // pdf
            "pdf",
            //    视频、音频
            "mp4", "mp3", "wav", "wmv", "ogg", "mp4", "mp3", "wav", "wmv", "ogg", "avi", "dat", "3gp", "mov", "rmvb"
    };

    public static final int DEFAULT_MAX_SIZE = 1024 * 1024 *1024;

    public String hashCodeSaveFile(MultipartFile uploadFile)throws FileUploadException{
        //解决文件名是绝对路径问题
        String fileName=uploadFile.getOriginalFilename();
        //获得文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //校验文件后缀
        if (!isExistsSuffix(suffix,DEFAULT_ALLOWED_EXTENSION)){
            throw new FileUploadException("不支持后缀为"+suffix+"的文件");
        }
        //校验文件大小
        long fileSize = uploadFile.getSize();
        if (uploadFile.getSize() > DEFAULT_MAX_SIZE){
            throw new FileUploadException("文件过大");
        }
        int index = fileName.lastIndexOf("\\");
        if(index!=-1){
            fileName = fileName.substring(index+1);
        }
        //解决文件同名问题
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String saveName = uuid+"_"+fileName;

        //根据原来的文件名获得hashCode并将其转化为16进制;
        int hashCode = fileName.hashCode();
        String hashCode1 = Integer.toHexString(hashCode);
        //根据前两位和绝对路径创建文件对象   mkdirs是创建文件链方法如果没有目录就创建如果有目录就不创建。
        String hashDir = hashCode1.charAt(0)+"/"+hashCode1.charAt(1) + "/" + hashCode1.charAt(2) + "/" + saveName;
        File file=new File(uploadDir,hashDir);
        if(!file.exists())
            file.mkdirs();
        try {
            uploadFile.transferTo(file);
            return hashDir;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断文件后缀
     * @param suffix 后缀
     * @param suffixTypes 后缀数组
     * @return
     */
    public boolean isExistsSuffix(String suffix,String[] suffixTypes){
        for (String suffixType : suffixTypes) {
            if (suffixType.equals(suffix))
                return true;
        }
        return false;
    }
}
